using System;
using System.Net;
using System.Reflection;
using System.Diagnostics;
using System.Windows.Forms;
using System.Text;
using System.IO;
using CSScriptLibrary;
using csscript;
//css_import credentials;

namespace Scripting
{
	class UpdateScript 
	{
		[STAThread]
		static public void Main(string[] args)
		{
			if (args.Length == 0 || args[0].ToLower() == "-?" || args[0].ToLower() == "/?")
				Console.WriteLine("Usage: cscscript soapsuds url file [/new] ...\nGenerates C# code for WebServiceClient.\n  /new - generate C# file only if it does not exist yet.\n\n"+
								  "The following sample creates proxy.dll assembly for MyRemotingClass type."+
								  "  Sample: cscscript soapsuds http://localhost:8080/MyRemotingApp/MyRemotingClass?WSDL proxy "+
								  "Always check if the remoting service is available with the IE: <url>\n");
			else
			{
				string wsdlExe = Environment.ExpandEnvironmentVariables(@"%CSSCRIPT_DIR%\lib\tools\soapsuds.exe");
				string url = args[0];
				string dllModule = (args[1].EndsWith(".dll") ? args[1] : (args[1] + ".dll"));
				dllModule = ResolveAsmLocation(dllModule);

				if (args.Length == 3 && (args[2].ToLower() == "/new" || args[2].ToLower() == "-new" || args[2].ToLower() == "new") && File.Exists(dllModule))
					return;

				bool useProxyAuthentication = false;
				while (true)
				{
					try
					{
						if (!File.Exists(wsdlExe))
							throw new FileNotFoundException("Cannot find " + wsdlExe + " utility.");

						string user = null, pw = null;
						if (useProxyAuthentication)
							if (!AuthenticationForm.GetCredentials(ref user, ref pw, "Proxy Authentication"))
								return;
						string test = "";
						if (TestURL(url, user, pw))
						{
							if (user != null)
								test = RunApp(wsdlExe, "-url:"+url+" \"-oa:"+dllModule+"\" \"-hpn:"+user+"\" \"-hpp:"+pw+"\" \"");
							else
								test = RunApp(wsdlExe, "-url:"+url+" \"-oa:"+dllModule+"\"");
						}
						if (!File.Exists(dllModule))
							throw new FileNotFoundException("Cannot create "+dllModule+" file.");
						return;
					}
					catch (Exception e)
					{
						if (e is System.Net.WebException && e.Message == "The remote server returned an error: (407) Proxy Authentication Required.")
						{
							if (useProxyAuthentication)
								Console.WriteLine(e.Message);

							useProxyAuthentication = true;
							continue;
						}
						throw e;
					}
				}
			}
		}
		static string ResolveAsmLocation(string file)
		{
			//System.Diagnostics.Debug.Assert(false);
            if (CSScript.GlobalSettings.HideAutoGeneratedFiles == Settings.HideOptions.HideAll)
				return Path.Combine(CSSEnvironment.GetCacheDirectory(CSSEnvironment.PrimaryScriptFile), Path.GetFileName(file));
			else
				return Path.Combine(Path.GetDirectoryName(CSSEnvironment.PrimaryScriptFile), file);
		}
		static bool TestURL(string url, string proxyUser, string proxyPw)
		{
			HttpWebRequest  request  = (HttpWebRequest)WebRequest.Create(url);
			if (proxyUser != null)
			{
				GlobalProxySelection.Select.Credentials = new NetworkCredential(proxyUser, proxyPw);
			}
			HttpWebResponse response = (HttpWebResponse)request.GetResponse();

			return true;
		}
		static string RunApp(string app, string args)
		{
			Process myProcess = new Process();
			myProcess.StartInfo.FileName = app;
			myProcess.StartInfo.Arguments = args;
			myProcess.StartInfo.WorkingDirectory = Environment.CurrentDirectory;
			myProcess.StartInfo.UseShellExecute = false;
			myProcess.StartInfo.RedirectStandardOutput = true;
			myProcess.StartInfo.CreateNoWindow = true;

			myProcess.Start();

			StringBuilder sb = new StringBuilder();
			string line = null;
			while (null != (line = myProcess.StandardOutput.ReadLine()))
			{
				sb.Append(line);
				sb.Append("\r\n");
			}
			myProcess.WaitForExit();
			return sb.ToString();
		}
	}
}